package com.demo.Controller;

import com.demo.entity.Grade;
import com.demo.entity.Student;
import com.demo.Repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/students")
public class StudentController {

    @Autowired
    private StudentRepository studentRepository;

    @GetMapping("/listAll")
    public List<Student> listAll() {
        return (List<Student>) studentRepository.findAll();
    }

    @GetMapping("/getById/{studentId}")
    public Optional<Student> getById(@PathVariable Long studentId) {
        return studentRepository.findById(studentId);
    }

    @PostMapping("/add")
    public Student add(@RequestBody Student student) {
        return studentRepository.save(student);
    }

    @GetMapping("/getGrades/{studentId}")
    public ResponseEntity<List<Grade>> getGrades(@PathVariable Long studentId) {
        Optional<Student> studentOptional = studentRepository.findById(studentId);
        if (studentOptional.isPresent()) {
            Student student = studentOptional.get();
            return ResponseEntity.ok(student.getGrades());
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}
//孙伟景220902011135